// 需要解决的问题？父组件 子组件 传值
import React, { createContext, useState } from 'react'
import classNames from 'classnames'

import { MenuItemProps } from './menuItem'

type MenuMode = 'horizontal' | 'vertical'

export interface MenuProps {
  // 默认高亮的菜单项的索引值
  defaultIndex?: number
  className?: string
  // 菜单类型 横向或者纵向
  mode?: MenuMode
  style?: React.CSSProperties
  // 点击菜单项 触发的回调函数
  onSelect?: (selectIndex: number) => void
}

// 需要传递的内容，通过 context 实现父传子
interface IMenuContext {
  index: number
  onSelect?: (selectIndex: number) => void
}
export const MenuContext = createContext<IMenuContext>({ index: 0 })

// Menu 主要是为网站提供导航功能的菜单，支持横向纵向两种模式，支持下拉菜单
const Menu: React.FC<MenuProps> = (props) => {
  const { className, mode, style, children, defaultIndex, onSelect } = props

  const [currentActive, setActive] = useState(defaultIndex)

  // 创建class
  const classes = classNames('tongyao-menu', className, {
    'menu-vertical': mode === 'vertical'
  })

  const handleClick = (index: number) => {
    setActive(index)
    if (onSelect) {
      onSelect(index)
    }
  }

  // 待传递的内容
  const passedContext: IMenuContext = {
    index: currentActive ? currentActive : 0,
    onSelect: handleClick
  }

  // 判断children合法性
  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<MenuItemProps>
      const { displayName } = childElement.type
      if (displayName === 'MenuItem') {
        // 自动添加 index
        return React.cloneElement(childElement, { index })
      } else {
        console.error('Warning: Menu has a child which is not a MenuItem component')
      }
    })
  }

  return (
    <ul className={classes} style={style} data-testid="test-menu">
      <MenuContext.Provider value={passedContext}>{renderChildren()}</MenuContext.Provider>
    </ul>
  )
}

Menu.defaultProps = {
  defaultIndex: 0,
  mode: 'horizontal'
}

export default Menu
